<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>扫码枪输入监听</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#F5F7FA',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .animate-pulse-slow {
                animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            .shadow-card {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
        }
    </style>
</head>
<body class="font-inter bg-neutral min-h-screen flex flex-col">
    <header class="bg-primary text-white shadow-md">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <h1 class="text-2xl font-bold flex items-center">
                <i class="fa fa-barcode mr-2"></i>扫码枪监听
            </h1>
            <div>
                <span id="status-indicator" class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
                    <span class="w-2 h-2 mr-2 bg-green-500 rounded-full animate-pulse"></span>
                    正在监听
                </span>
            </div>
        </div>
    </header>

    <main class="flex-grow container mx-auto px-4 py-8">
        <div class="max-w-3xl mx-auto bg-white rounded-xl shadow-card p-6 md:p-8 transform transition-all hover:shadow-lg">
            <div class="mb-6">
                <h2 class="text-xl font-semibold text-dark mb-2">扫码结果</h2>
                <div id="scan-result" class="min-h-[100px] bg-neutral rounded-lg p-4 text-dark border border-gray-200 overflow-auto">
                    <p class="text-gray-500 italic">等待扫码...</p>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-blue-50 rounded-lg p-4 border border-blue-100">
                    <h3 class="font-medium text-blue-800 mb-1 flex items-center">
                        <i class="fa fa-clock-o mr-2"></i>最后扫码时间
                    </h3>
                    <p id="last-scan-time" class="text-gray-700">--</p>
                </div>
                <div class="bg-green-50 rounded-lg p-4 border border-green-100">
                    <h3 class="font-medium text-green-800 mb-1 flex items-center">
                        <i class="fa fa-list-ol mr-2"></i>扫码总数
                    </h3>
                    <p id="scan-count" class="text-gray-700">0</p>
                </div>
                <div class="bg-purple-50 rounded-lg p-4 border border-purple-100">
                    <h3 class="font-medium text-purple-800 mb-1 flex items-center">
                        <i class="fa fa-tachometer mr-2"></i>扫描速度
                    </h3>
                    <p id="scan-speed" class="text-gray-700">--</p>
                </div>
            </div>

            <div class="flex justify-between items-center">
                <button id="clear-btn" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center">
                    <i class="fa fa-trash-o mr-2"></i>清空记录
                </button>
                <div class="text-sm text-gray-500">
                    <i class="fa fa-info-circle mr-1"></i>
                    <span>将自动识别快速连续输入</span>
                </div>
            </div>
        </div>
    </main>

    <footer class="bg-dark text-white py-4">
        <div class="container mx-auto px-4 text-center">
            <p>扫码枪监听工具 &copy; 2025</p>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 扫码枪配置
            const config = {
                codeDelay: 1,       // 字符输入间隔小于此值（毫秒）时被认为是扫码枪输入
                endDelay: 100,       // 扫码结束的延迟时间（毫秒）
                minLength: 3         // 最小有效条码长度
            };

            // 状态变量
            let scanBuffer = '';      // 扫描缓冲区
            let lastKeyTime = 0;      // 上次按键时间
            let scanTimer = null;     // 扫描结束计时器
            let scanCount = 0;        // 扫描计数
            let lastScanTime = null;  // 上次扫描时间
            let scanSpeed = 0;        // 扫描速度（字符/秒）

            // DOM 元素
            const scanResultEl = document.getElementById('scan-result');
            const lastScanTimeEl = document.getElementById('last-scan-time');
            const scanCountEl = document.getElementById('scan-count');
            const scanSpeedEl = document.getElementById('scan-speed');
            const clearBtn = document.getElementById('clear-btn');

            // 格式化日期时间
            function formatDateTime(date) {
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            }

            // 处理扫码结果
            function handleScanResult(code) {
                // 增加扫描计数
                scanCount++;

                // 计算扫描速度
                const timeDiff = Date.now() - lastKeyTime + config.endDelay;
                scanSpeed = Math.round((code.length / timeDiff) * 1000);

                // 更新上次扫描时间
                lastScanTime = new Date();

                // 更新显示
                updateDisplay(code);
            }

            // 更新显示
            function updateDisplay(code) {
                // 添加新的扫描结果
                const resultItem = document.createElement('div');
                resultItem.className = 'mb-3 p-2 rounded bg-white border border-gray-200 hover:bg-gray-50 transition-colors';

                const timestamp = document.createElement('div');
                timestamp.className = 'text-xs text-gray-500 mb-1';
                timestamp.textContent = formatDateTime(lastScanTime);

                const codeValue = document.createElement('div');
                codeValue.className = 'font-medium break-all';
                codeValue.textContent = code;

                resultItem.appendChild(timestamp);
                resultItem.appendChild(codeValue);

                // 清空初始提示文本
                if (scanResultEl.querySelector('p.italic')) {
                    scanResultEl.innerHTML = '';
                }

                console.log(code);
                // 添加新结果到顶部
                scanResultEl.insertBefore(resultItem, scanResultEl.firstChild);

                // 更新统计信息
                lastScanTimeEl.textContent = formatDateTime(lastScanTime);
                scanCountEl.textContent = scanCount;
                scanSpeedEl.textContent = `${scanSpeed} 字符/秒`;

                // 添加动画效果
                resultItem.classList.add('animate-pulse-slow');
                setTimeout(() => {
                    resultItem.classList.remove('animate-pulse-slow');
                }, 1000);
            }

            // 清空记录
            clearBtn.addEventListener('click', () => {
                scanResultEl.innerHTML = '<p class="text-gray-500 italic">等待扫码...</p>';
                scanCount = 0;
                scanCountEl.textContent = '0';
            });

            // 键盘事件监听
            document.addEventListener('keydown', (e) => {
                const now = Date.now();
                const timeDiff = now - lastKeyTime;
                lastKeyTime = now;

                // 忽略系统按键
                if (e.ctrlKey || e.altKey || e.metaKey) return;

                // 如果距离上次按键时间较长，清空缓冲区
                if (timeDiff > config.endDelay) {
                    scanBuffer = '';
                    if (scanTimer) clearTimeout(scanTimer);
                }

                // 添加字符到缓冲区（忽略回车键，它通常是扫码的结束符）
                if (e.key !== 'Enter') {
                    scanBuffer += e.key;
                }

                // 清除之前的计时器
                if (scanTimer) clearTimeout(scanTimer);

                // 设置新的计时器来检测扫码结束
                scanTimer = setTimeout(() => {
                    // 检查是否是有效的扫码结果
                    if (scanBuffer.length >= config.minLength) {
                        handleScanResult(scanBuffer);
                    }
                    scanBuffer = '';
                }, config.endDelay);
            });
        });
    </script>
</body>
</html>
